<?php

namespace addons\alisms;

use AlibabaCloud\Client\AlibabaCloud;
use buwang\base\BaseAddons;
use think\Exception;
use think\exception\HttpException;

/**
 * 阿里云短信插件
 * @author byron sampson
 */
class Plugin extends BaseAddons    // 需继承think\Addons类
{
    // 该插件的基础信息
    public $info = [
    ];
    /**
     * 插件安装方法
     * @return bool
     */
    public function install()
    {
        return true;
    }

    /**
     * 插件卸载方法
     * @return bool
     */
    public function uninstall()
    {
        return true;
    }
    public function enabled()
    {
        // TODO: Implement enabled() method.
    }
    public function disabled()
    {
        // TODO: Implement disabled() method.
    }

    /**
     * 发送验证码
     * @param $param
     * @return bool
     * @throws Exception
     * @throws \AlibabaCloud\Client\Exception\ClientException
     * @throws \AlibabaCloud\Client\Exception\ServerException
     */
    public function alismsSendHook($param)
    {
        if(!isset($param['mobile']) || !$param['mobile']) throw new Exception('请填写正确的手机号');
        if(!isset($param['code']) || !$param['code']) throw new Exception('请填写正确的验证码');

        $config = $this->getConfig();

        AlibabaCloud::accessKeyClient($config['key'], $config['secret'])
            ->regionId('cn-hangzhou')
            ->asDefaultClient();
        $result = AlibabaCloud::rpc()
            ->product('Dysmsapi')
            // ->scheme('https') // https | http
            ->version('2017-05-25')
            ->action('SendSms')
            ->method('POST')
            ->host('dysmsapi.aliyuncs.com')
            ->options([
                'query' => [
                    'RegionId' => "cn-hangzhou",
                    'SignName' => $config['sign'],
                    'TemplateCode' => $config['template'],

                    'PhoneNumbers' => $param['mobile'],
                    'TemplateParam' => json_encode(['code' => $param['code']]),
                ],
            ])
            ->request();
        $result = $result->toArray();

        if (isset($result['Code']) && $result['Code'] == 'OK') return true;
        else {
            $e = new \Exception(isset($result['Message']) ? $result['Message'] : '阿里云短信服务异常');
            throw $e;
        }
    }
    public function addon_middleware($request){
        //$request->rule()->middleware(\buwang\middleware\AddonsLoginMiddleware::class);
        //echo "{$this->getName()}执行了插件方法：addon_middleware".PHP_EOL;
        //throw new HttpException(404, "请进行登录操作");
    }
}